//
//  ArchiveDemo.swift
//  firstProject
//
//  Created by 张彦辉 on 2017/5/4.
//  Copyright © 2017年 张彦辉. All rights reserved.
//

import UIKit

class ArchiveDemo: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = UIColor.white
        
        let setBut = UIButton()
        setBut.backgroundColor = UIColor.blue
        setBut.setTitle("设置", for: .normal)
        setBut.addTarget(self, action: #selector(setButClick), for: .touchUpInside)
        
        let getBut = UIButton()
        getBut.backgroundColor = UIColor.darkGray
        getBut.setTitle("读取", for: .normal)
        getBut.addTarget(self, action: #selector(getButClick), for: .touchUpInside)
        
        self.view.addSubview(setBut)
        self.view.addSubview(getBut)
        
        setBut.snp.makeConstraints { (maker) in
            maker.top.equalTo(100)
            maker.left.equalTo(10)
        }
        getBut.snp.makeConstraints { (maker) in
            maker.top.equalTo(setBut)
            maker.left.equalTo(setBut.snp.right).offset(7)
        }

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    func setButClick() -> Void {
        
        //创建对象
        let student = Student(sno: "1101", name: "lisi", score: Int(arc4random() % 100))
        //构造路径
        let path = "\(Constant.documentPath)/student.archive"
        //归档对象
        if NSKeyedArchiver.archiveRootObject(student, toFile: path) {
            PublicUtil.alert(obj: self, title: "提示", msg: "保存成功")
        }else{
            PublicUtil.alert(obj: self, title: "提示", msg: "保存失败")
        }
        
    }
    func getButClick() -> Void {
        let path = "\(Constant.documentPath)/student.archive"
        //解档对象
        if let obj = NSKeyedUnarchiver.unarchiveObject(withFile: path) {
            let stu = obj as! Student
            PublicUtil.alert(obj: self, title: "提示", msg: "学号：\(stu.sno!),姓名：\(stu.name!),成绩：\(stu.score!)")
        }else{
            PublicUtil.alert(obj: self, title: "提示", msg: "解档失败")
        }
    }
}

class Student: NSObject, NSCoding{
    var sno: String!
    var name: String!
    var score: Int!
    init(sno: String, name: String, score: Int) {
        self.sno = sno
        self.name = name
        self.score = score
    }
    // MARK: - 处理需要归档的字段
    func encode(with aCoder: NSCoder){
        aCoder.encode(sno, forKey: "sno")
        aCoder.encode(name, forKey: "name")
        aCoder.encode(score, forKey: "score")
    }
    
    // MARK: - 处理需要解档字段
    required init?(coder aDecoder: NSCoder){
        super.init()
        self.sno = aDecoder.decodeObject(forKey: "sno") as! String
        self.name = aDecoder.decodeObject(forKey: "name") as! String
        self.score = aDecoder.decodeObject(forKey: "score") as! Int
    }
    override init() {
        super.init()
    }
}
